<?php

namespace App\Models\Api;

use Illuminate\Database\Eloquent\Model;

class Address extends Model
{

    protected $table = 'address';
    protected $primaryKey = 'id';
    protected $dateFormat = 'U';// 时间戳
    protected $casts = [
        'created_at' => 'datetime:Y-m-d H:i:s',
        'updated_at' => 'datetime:Y-m-d H:i:s'
    ];

    /**
     * 获取详情
     * @param $id
     * @param $store_id
     */
    public static function getInfoById($id, $store_id)
    {
        $info = self::where(['client_id' => $store_id, 'id' => $id, 'type' => 1])->first();
        if ($info) {
            return $info->toArray();
        }
        return [];
    }

    /**
     * 获取默认地址详情
     * @param $id
     * @param $store_id
     */
    public static function getDefaultBySId($store_id)
    {
        $info = self::where(['client_id' => $store_id, 'deafult' => 1, 'type' => 1])->first();
        if ($info) {
            return $info->toArray();
        }
        return [];
    }

    /**
     * 获取列表
     * @param $store_id
     */
    public static function getListBySid($store_id)
    {
        $list = self::where(['client_id' => $store_id, 'type' => 1])->get()->toArray();
        return $list;
    }

    /**
     * 编辑信息
     * @param $dataArr
     */
    public static function editInfo($store_id, $dataArr)
    {
        $num = self::where(['client_id' => $store_id, 'type' => 1])->count();
        if ($num == 0) {
            $dataArr['deafult'] = 1;
        } else {
            if ($dataArr['deafult'] == 1) {
                self::where(['client_id' => $store_id, 'type' => 1])->update(['deafult' => 0]);
            }
        }
        $info['client_id'] = $store_id;
        $info['name'] = $dataArr['name'];
        $info['mobile'] = $dataArr['mobile'];
        $info['province'] = $dataArr['province'];
        $info['city'] = $dataArr['city'];
        $info['area'] = $dataArr['area'];
        $info['address'] = $dataArr['address'];
        $info['postcode'] = $dataArr['postcode'];
        $info['remark'] = $dataArr['remark'];
        $info['deafult'] = $dataArr['deafult'] ?: 0;
        $info['type'] = 1;
        if ($dataArr['id']) {
            return self::where(['id' => $dataArr['id'], 'client_id' => $store_id])->update($info);
        } else {
            $info['created_at'] = time();
            return self::insert($info);
        }
    }
}
